package com.example.housingRentalSystem.service.Impl;

import com.example.housingRentalSystem.bean.House;
import com.example.housingRentalSystem.bean.Order;
import com.example.housingRentalSystem.bean.OrderConstants;
import com.example.housingRentalSystem.mapper.HouseMapper;
import com.example.housingRentalSystem.mapper.OrderMapper;
import com.example.housingRentalSystem.service.OrderService;
import com.example.housingRentalSystem.utils.PageRequest;
import com.example.housingRentalSystem.utils.PageResponse;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.sql.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private HouseMapper houseMapper;

    @Override
    @Transactional
    public Order createOrder(Order order) {


        // 从order对象获取数据
        House house = houseMapper.selectHouseById(order.getHouseId());
        if (house == null || house.getStatus() != 1) {
            throw new RuntimeException("房屋不可出租");
        }

        validateDates(order.getStartDate(), order.getEndDate());
        int days = calculateDays(order.getStartDate(), order.getEndDate());
        int total = calculateTotal(house.getMonthRent(), days);

        order.setOrderNumber("Order"+order.getCustomerId()+generateOrderNumber()+System.currentTimeMillis());
        order.setOwnerId(house.getOwnerId());
        order.setStatus(OrderConstants.TO_BE_SIGNED);
        order.setDayNum(days);
        order.setTotalAmount(total);
        order.setCreateTime(new Date(System.currentTimeMillis()));

        orderMapper.insert(order);
        return order;
    }

    @Override
    @Transactional
    public void processPayment(Integer orderId,Integer houseId) {
        orderMapper.updateStatus(orderId, OrderConstants.EFFECTIVE);
        houseMapper.updateHouseStatus(houseId, 2);
    }

    @Override
    @Transactional
    public void confirmOrder(Integer orderId) {
        orderMapper.updateStatus(orderId, OrderConstants.TO_BE_PAID);
    }

    @Override
    public void cancelOrder(Integer orderId, String reason) {
        if (reason == null || reason.trim().isEmpty()) {
            throw new IllegalArgumentException("必须填写取消原因");
        }
        int rows = orderMapper.updateCancelInfo(
                orderId,
                3,
                reason
        );
        if (rows == 0) {
            throw new RuntimeException("订单取消失败");
        }
    }

    @Override
    public void agreeOrder(Integer orderId) {
        orderMapper.updateStatus(orderId, OrderConstants.COMPLETED);
    }

    @Override
    public void refuseOrder(Integer orderId, String refusalReason) {
        if (refusalReason == null || refusalReason.trim().isEmpty()) {
            throw new IllegalArgumentException("必须填写拒绝原因");
        }
        orderMapper.refusalReason(orderId,  refusalReason,2);
    }


    @Override
    public PageResponse<Order> searchOrders(Integer customerId, Integer ownerId,
                                            Integer houseId, Integer status,
                                            PageRequest pageRequest) {

        // 启动分页
        PageHelper.startPage(
                pageRequest.getPage(),
                pageRequest.getSize(),
                pageRequest.getSortField() + " " + pageRequest.getSortOrder()
        );

        // 执行查询
        List<Order> orders = orderMapper.searchOrders(customerId, ownerId, houseId, status);

        // 转换分页结果
        return PageResponse.build((Page<Order>) orders);
    }

    @Override
    public Order getOrderById(Integer id) {
        Order order = orderMapper.getOrderById(id);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        return order;
    }

    @Override
    public void refuseOrder(Integer orderId) {
        orderMapper.updateStatus(orderId, OrderConstants.EFFECTIVE);
    }

    private void validateDates(Date start, Date end) {
        if (start.after(end)) {
            throw new RuntimeException("开始日期不能晚于结束日期");
        }
        if (start.before(today())) {
            throw new RuntimeException("不能选择过去的日期");
        }
    }

    private int calculateDays(Date start, Date end) {
        return (int) ((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24));
    }

    private int calculateTotal(Integer monthRent, int days) {
        return (int) (monthRent / 30.0 * days);
    }

    private Date today() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return new java.sql.Date(cal.getTimeInMillis());
    }

    private Integer generateOrderNumber() {
        return (int) (System.currentTimeMillis() % 1000000000L);
    }


}